package com.example.kotlintest.chat;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.kotlintest.R;
import com.example.kotlintest.chat.adapter.BottomMenuAdapter;
import com.example.kotlintest.chat.adapter.ChatUIManager;
import com.example.kotlintest.chat.adapter.MaskAdapter;
import com.example.kotlintest.chat.adapter.MessageAdapter;
import com.example.kotlintest.chat.listener.ChatEditListener;
import com.example.kotlintest.chat.listener.KeyboardWatcher;
import com.guoxiaoxing.phoenix.core.listener.ImageLoader;
import com.ilike.voicerecorder.service.PlayService;
import com.ilike.voicerecorder.service.PlayServiceConnection;
import com.ilike.voicerecorder.utils.AppCache;
import com.ilike.voicerecorder.utils.PathUtil;
import com.ilike.voicerecorder.widget.VoiceRecorderView;

import java.security.Permission;
import java.security.Permissions;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class ChatActivity extends AppCompatActivity implements KeyboardWatcher.OnKeyboardToggleListener {
    RecyclerView rvBottom;
    RecyclerView rcMsgs;
    View vLastLine;
    ImageView ivEditOrVoice;
    ImageView ivMask;
    ImageView ivAdd;
    TextView btVoice;
    EditText edMsg;
    TextView tvSend;
    VoiceRecorderView voiceRecorderView;
    private KeyboardWatcher mKeyboardWatcher;
    private PlayServiceConnection playServiceConnection;

    private MessageAdapter adapter;
    //添加菜单是否弹出
    private boolean isAdd=false;

    private ChatUIManager uiManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        //检测键盘状态
        mKeyboardWatcher=new KeyboardWatcher(this);
        mKeyboardWatcher.setListener(this);
        //音频播放服务绑定
        Intent intent=new Intent();
        intent.setClass(this, PlayService.class);
        playServiceConnection=new PlayServiceConnection();
        bindService(intent,playServiceConnection,Context.BIND_AUTO_CREATE);
        //初始化视图
        init();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mKeyboardWatcher.destroy();
        mKeyboardWatcher=null;
        unbindService(playServiceConnection);
    }
    final int[] count = {0};
    private void init(){

        //获取权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,"android.permission.READ_PHONE_STATE","android.permission.RECORD_AUDIO"},10001);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivity(intent);
                return;
            }
        }

        rvBottom=this.findViewById(R.id.rcBootom);
        rcMsgs=this.findViewById(R.id.rcMsgs);
        vLastLine=this.findViewById(R.id.vLastLine);
        ivEditOrVoice=this.findViewById(R.id.ivEditOrVoice);
        ivMask=this.findViewById(R.id.ivMask);
        ivAdd=this.findViewById(R.id.ivAdd);
        btVoice=this.findViewById(R.id.btVoice);
        edMsg=this.findViewById(R.id.edMsg);
        tvSend=this.findViewById(R.id.tvSend);
        voiceRecorderView=this.findViewById(R.id.voice_recorder);

        //设置录音显示事件
        voiceRecorderView.setShowMoveUpToCancelHint("向上滑动手指停止录音");
        voiceRecorderView.setShowReleaseToCancelHint("松开手指取消发送");
        voiceRecorderView.setToShortNotis("你说话时间太短");
        voiceRecorderView.setNoPermissionNotis("没有获取权限");
//        voiceRecorderView.reSize(500,500);
        voiceRecorderView.reTextSize(14);
        voiceRecorderView.reImgSize(150,200);
        voiceRecorderView.setMaxRecord(60);

        PathUtil.getInstance().createDirs("chat", "voice", this);

        uiManager=new ChatUIManager(this,ivEditOrVoice,btVoice,edMsg,ivMask,ivAdd,rvBottom,tvSend);

        btVoice.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new VoiceRecorderView.EaseVoiceRecorderCallback() {

                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        Log.e("voiceFilePath=", voiceFilePath + "  time = " + voiceTimeLength);
                        /**
                         *voiceFilePath 为录音文件存放在sd的路径
                         * voiceTimeLength 录音文件的时长
                         */
                        count[0]++;
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        if(count[0]%3!=0){
                            MsgEntity msg = new MsgEntity(MsgEntity.MSG_TYPE_AUDIO, "10001", "10002", voiceFilePath, sdf.format(new Date()));
                            adapter.addMsg(msg);
//                        }else{
//                            MsgEntity msg = new MsgEntity(MsgEntity.MSG_TYPE_AUDIO, "10002", "10001", voiceFilePath, sdf.format(new Date()));
//                            adapter.addMsg(msg);
//                        }
                    }
                });
            }
        });
        //添加图标点击事件
        ivAdd.setOnClickListener((v)->{
            //如果菜单已被隐藏且当前状态为未打开则加载菜单栏
//            if(rvBottom.getVisibility()==View.GONE||!isAdd){
//                //设置为添加菜单打开状态
//                isAdd=true;
//                //隐藏输入法
//                hideInputMethod(edMsg);
//                //让底部添加菜单的recycleview显示出来
//                rvBottom.setVisibility(View.VISIBLE);
//                //底部添加菜单分割线显示
//                vLastLine.setVisibility(View.VISIBLE);
//                //按住说话按钮隐藏
//                btVoice.setVisibility(View.GONE);
//                //输入框显示
//                edMsg.setVisibility(View.VISIBLE);
//                //恢复左侧语音或者输入按钮图标的显示为默认
//                ivEditOrVoice.setBackground(getDrawable(R.drawable.icon_voice));
//                //加载底部菜单适配器
//                BottomMenuAdapter.init(ChatActivity.this, rvBottom, new BottomMenuAdapter.OnItemClickListener() {
//                    @Override
//                    public void itemClick(BottomMenuAdapter.MenuHolder menuHolder, int postion) {
//                        Toast.makeText(ChatActivity.this,"点击了菜单："+postion,Toast.LENGTH_SHORT).show();
//                        switch (postion){
//                            case 0:
//                                PhotoPicker.init(new ImageLoader() {
//                                    @Override
//                                    public void loadImage(Context context, ImageView imageView, String s, int i) {
//                                        Glide.with(context)
//                                                .load(s)
//                                                .into(imageView);
//                                    }
//                                });
//                                PhotoPicker photoPicker=new PhotoPicker();
//                                photoPicker.setMaxPickNumber(1);
//                                photoPicker.setCallback(new PhotoPicker.photoPickerBack() {
//                                    @Override
//                                    public void getFinalPath(@NonNull List<String> arrayList, @NonNull List<String> arrayList1, @NonNull List<String> arrayList2) {
//                                        if(arrayList.size()>0) {
//                                            SpannableString ss=EmojiUtils.getFileMask(ChatActivity.this, arrayList.get(0));
//                                            if(edMsg.getText().length()==0){
//                                                edMsg.append(ss);
//                                            }else{
//                                                int start=edMsg.getSelectionStart();
//                                                int end=edMsg.getSelectionEnd();
//                                                edMsg.getText().replace(Math.min(start,end),Math.max(start,end),ss,0,ss.length());
//                                            }
////                                            edMsg.setSelection(edMsg.getText().length());
//                                        }
//                                    }
//                                });
//                                PhotoPicker.show(ChatActivity.this,0,new ArrayList<String>());
//                                break;
//                        }
//                    }
//                });
//                //让消息记录recycleview滑动到底部
                toBottom();
//            }else{
//                //显示输入法，有可能不生效
//                showInputMethod(edMsg);
//            }
            uiManager.ivAdd();
        });
        //左侧编辑或者语音图标点击事件
        ivEditOrVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果当前是编辑状态则显示语音按钮
//                if(btVoice.getVisibility()==View.GONE){
//                    //隐藏输入法
//                    hideInputMethod(edMsg);
//                    //按住说话按钮显示
//                    btVoice.setVisibility(View.VISIBLE);
//                    //消息编辑框隐藏
//                    edMsg.setVisibility(View.GONE);
//                    //底部添加菜单的recycleview隐藏
//                    rvBottom.setVisibility(View.GONE);
//                    //分割线隐藏
//                    vLastLine.setVisibility(View.GONE);
//                    //左侧编辑或者语音按钮图标变为键盘图标
//                    ivEditOrVoice.setBackground(getDrawable(R.drawable.icon_key));
//                    //右侧添加图标显示
//                    ivAdd.setVisibility(View.VISIBLE);
//                    //消息发送按钮隐藏
//                    tvSend.setVisibility(View.GONE);
//                    //滑动到底部
                    toBottom();
//                }else{
//                    //按住说话按钮隐藏
//                    btVoice.setVisibility(View.GONE);
//                    //消息编辑框显示
//                    edMsg.setVisibility(View.VISIBLE);
//                    //左侧编辑或者语音按钮图标变为语音图标
//                    ivEditOrVoice.setBackground(getDrawable(R.drawable.icon_voice));
//                    //如果消息编辑框有信息，则把添加图标隐藏，发送按钮显示
//                    if(edMsg.getText().length()>0) {
//                        ivAdd.setVisibility(View.GONE);
//                        tvSend.setVisibility(View.VISIBLE);
//                    }
//                    //显示输入法
//                    showInputMethod(edMsg);
//                }
                uiManager.leftIcon();
            }
        });
        //初始化消息适配器
        adapter=MessageAdapter.init(rcMsgs, this, new MessageAdapter.OnItemClickListener() {
            @Override
            public void itemClick(MessageAdapter.MessageHodler menuHolder, int postion) {
                MsgEntity msg=adapter.getData(postion);
                //判断是自己的音频
                if(msg.getMsgType()==MsgEntity.MSG_TYPE_AUDIO){
                    if(msg.getMsgOwer().equals("10001")) {
                        AppCache.getPlayService().setImageView(menuHolder.ivVoice);
                        AppCache.getPlayService().setPlayStopDrawable(R.drawable.ease_chatto_voice_playing_f3);
                        AppCache.getPlayService().setVoiceAnimation(R.drawable.voice_to_icon);
                    }else{
                        AppCache.getPlayService().setImageView(menuHolder.ivVoiceLeft);
                        AppCache.getPlayService().setPlayStopDrawable(R.drawable.icon_left_play_2);
                        AppCache.getPlayService().setVoiceAnimation(R.drawable.voice_to_icon_left);
                    }
                    AppCache.getPlayService().play(msg.getContent());
                }
            }
        });
        toBottom();
        //监听文本输入情况
        final boolean[] isDel = {false};
        edMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.e(TAG, "beforeTextChanged: "+i+","+i1+","+i2 );
                isDel[0] =(i1>0);
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.e(TAG, "onTextChanged: "+charSequence );
            }

            @Override
            public void afterTextChanged(Editable editable) {
                //如果输入了文字就把添加图标变成发送按钮
                if(editable.length()>0){
                    tvSend.setVisibility(View.VISIBLE);
                    ivAdd.setVisibility(View.GONE);
                }else{
                    tvSend.setVisibility(View.GONE);
                    ivAdd.setVisibility(View.VISIBLE);
                }
                //针对小米6等手机处理的删除方案
                if(isDel[0]){
                    Log.e(TAG, "afterTextChanged1: "+isDel[0] );
                    Editable edtxt=editable;
                    int start=edMsg.getSelectionStart();
                    int end=edMsg.getSelectionEnd();
                    Log.e(TAG, "afterTextChanged2: "+start );
                    Log.e(TAG, "afterTextChanged3: "+end );
                    String endPrefix="]";
                    char endPrefixChar = endPrefix.charAt(0);
                    char startPrefix = "[".charAt(0);
                    int lastIndex = start-1;
                    int getStr= EmojiUtils.findIndexFromEnd(edtxt.toString(),lastIndex,startPrefix);
                    Log.e(TAG, "afterTextChanged4: "+getStr );
                    Log.e(TAG, "afterTextChanged5: "+lastIndex );
                    if(getStr<lastIndex) {
                        String emojiStr = edtxt.toString().substring(getStr, lastIndex + 1);
                        Log.e(TAG, "afterTextChanged5-1: " + emojiStr);
                        if(emojiStr.contains(endPrefix)){
                            Log.e(TAG, "afterTextChanged6: " + emojiStr);
                            Log.e(TAG, "afterTextChanged7: 校验失败，不继续往下删除" );
                            return;
                        }
                        Log.e(TAG, "afterTextChanged6: " + emojiStr.concat(endPrefix));
                        if(EmojiUtils.getEmojiPosition(emojiStr.concat(endPrefix))>-1||emojiStr.startsWith(EmojiUtils.filePrefixStart)){
                            Log.e(TAG, "afterTextChanged7: 是表情或者文件" );
                            edtxt.delete(getStr,start);
                        }
                    }
                }
            }
        });
        //消息发送按钮点击事件
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String filePrefix="[file://";
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String msgTxt=edMsg.getText().toString();
                Log.e(TAG, "onClick: "+ msgTxt);
                if(msgTxt.length()>0&& !msgTxt.contains(filePrefix)){
                    Log.e(TAG, "onClick: 没有文件");
                    MsgEntity msg=new MsgEntity(MsgEntity.MSG_TYPE_TXT,"10001","10002",edMsg.getText().toString(),sdf.format(new Date()));
                    adapter.addMsg(msg);
                    tvSend.setVisibility(View.GONE);
                    ivAdd.setVisibility(View.VISIBLE);
                    edMsg.setText("");
                    toBottom();
                }else if(msgTxt.length()>0&& msgTxt.contains(filePrefix)){
                    Log.e(TAG, "onClick: 有文件");
                    List<String>files=EmojiUtils.getFilesPathInMsg(msgTxt);
                    for (String file : files) {
                        Log.e(TAG, "onClick: "+file );
                        MsgEntity msgEntity=new MsgEntity(MsgEntity.MSG_TYPE_IMG,"10001","10002",file,sdf.format(new Date()));
                        adapter.addMsg(msgEntity);
                    }
                    String lastMsg=EmojiUtils.getTextInFileMsg(msgTxt);
                    if(!TextUtils.isEmpty(lastMsg)) {
                        MsgEntity txtEntity = new MsgEntity(MsgEntity.MSG_TYPE_TXT, "10001", "10002", lastMsg, sdf.format(new Date()));
                        adapter.addMsg(txtEntity);
                    }

                    tvSend.setVisibility(View.GONE);
                    ivAdd.setVisibility(View.VISIBLE);
                    edMsg.setText("");
                    toBottom();
                }
            }
        });
        //选择表情图标点击事件
        ivMask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toBottom();
                uiManager.ivMask();
            }
        });
        edMsg.setOnKeyListener(new ChatEditListener(this));
    }


    private static final String TAG = "ChatActivity";
    @Override
    public void onKeyboardShown(int keyboardSize) {
        Log.e(TAG, "onKeyboardShown: " );
        uiManager.keyboardShow();
        toBottom();
    }
    //消息列表滑动到底部
    private void toBottom(){
        rcMsgs.post(new Runnable() {
            @Override
            public void run() {
                rcMsgs.scrollToPosition(adapter.getSize()-1);
            }
        });
    }

    @Override
    public void onKeyboardClosed() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if(Environment.isExternalStorageManager()){
                init();
            }
        }
    }
}